package com.king.first.app.watermark;

import com.king.first.bean.WaterSensor;
import com.king.first.utils.ContentUtils;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

public class Flink11_Watermark_Period {

    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env
                .socketTextStream(ContentUtils.HOST, 9999)  // 在socket终端只输入毫秒级别的时间戳
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] datas = value.split(",");
                        return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));

                    }
                });

        // 自定义水印
        WatermarkStrategy<WaterSensor> watermarkStrategy = new WatermarkStrategy<WaterSensor>() {
            @Override
            public WatermarkGenerator<WaterSensor> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) {
                System.out.println("createWatermarkGenerator ....");
                return new MyPeriod(3);
            }
        }.withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
            @Override
            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                return element.getTs() * 1000;
            }
        });

        WindowedStream<WaterSensor, String, TimeWindow> windowWindowedStream =
                waterSensorStream.assignTimestampsAndWatermarks(watermarkStrategy)
                .keyBy(value -> value.getId())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)));

        windowWindowedStream.sum("vc").print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * 周期水印
 */
class MyPeriod implements WatermarkGenerator<WaterSensor>{

    private long maxTs = Long.MIN_VALUE;
    // 允许的最大延迟时间 ms
    private final long maxDelay;

    public MyPeriod(long maxDelay){
        this.maxDelay = maxDelay * 1000;
        this.maxTs = Long.MIN_VALUE + this.maxDelay + 1;
    }

    @Override
    public void onEvent(WaterSensor event, long eventTimestamp, WatermarkOutput output) {
        System.out.println("onEvent..." + eventTimestamp);
        //有了新的元素找到最大的时间戳
        maxTs = Math.max(maxTs, eventTimestamp);
        System.out.println(maxTs);
    }

    @Override
    public void onPeriodicEmit(WatermarkOutput output) {
        // 周期性的发射水印: 相当于Flink把自己的时钟调慢了一个最大延迟
        output.emitWatermark(new Watermark(maxTs - maxDelay - 1));
    }
}